package me.yobol.blog.util.sql;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnectionFactory {
	
	private final static ConnectionFactory factory = new ConnectionFactory();
	private static String driver,
						  dburl,
						  user,
						  password;
	private Connection ctn = null;
	
	static{
		//Properties类用来处理属性文件里的键值对
		Properties prop = new Properties();
		try {
			//将dbconfig.properties属性文件作为输入流加载到ConnectionFactory.class中
			InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("dbconfig.properties");
			prop.load(in);
		} catch (Exception e) {
			System.out.println("======== dbconfig.properties属性文件加载失败 ========");
			e.printStackTrace();
		}finally{
			driver = prop.getProperty("driver");
			dburl = prop.getProperty("dburl");
			user = prop.getProperty("user");
			password = prop.getProperty("password");
		}
	}
	
	private ConnectionFactory(){}
	
	public static ConnectionFactory getInstance(){
		return factory;
	}
	
	public Connection getConnection(){
		try{
			//注册并加载驱动
			Class.forName(driver);
			ctn = (com.mysql.jdbc.Connection) DriverManager.getConnection(dburl,user,password);
		}catch(Exception e){
			System.out.println("======== 驱动加载失败 ========");
			e.printStackTrace();
		}
		return ctn;
	}
}
